package castledefense.logic.pathfinding;

import java.util.ArrayList;

import castledefense.util.Log;

import pathfinding.grid.GridPath;

public class PathfindingThreadUnit implements Runnable{
	
	private ArrayList<PositionMover> unitList = new ArrayList<PositionMover>();
	private ArrayList<PositionMover> unitList2 = new ArrayList<PositionMover>();
	private ArrayList<PositionMover> unitList3 = new ArrayList<PositionMover>();
	private LinkForPathfinding link;
	private Pathfinding pathfinding;
	
	public PathfindingThreadUnit(LinkForPathfinding link){
		this.link = link;
		pathfinding = new Pathfinding(link);
	}
	
	public synchronized void addUnit(PositionMover pos){
		unitList2.add(pos);
	}
	
	public synchronized void removeUnit(PositionMover pos){
		unitList3.add(pos);
	}

	@Override
	public void run() {
		while(true){
			mergeList();
			removeUnitList();
			update();
			try {
				Thread.sleep(15);
			} catch (InterruptedException e) {
				//Do nothing
			}
		}
	}
	
	private synchronized void removeUnitList(){
		unitList.removeAll(unitList3);
		unitList3.clear();
	}

	private synchronized void mergeList() {
		unitList.addAll(unitList2);
		unitList2.clear();
	}

	private void update() {
		int n = 0;
		while(unitList.size() > 0 && n++ <10){
			PositionMover position = unitList.remove(0);
			long timeBefore = System.nanoTime();
			GridPath path = pathfinding.getPath(position, link.getCastleX(), link.getCastleY());
			long timeAfter = System.nanoTime();
			int time = (int) ((timeAfter - timeBefore)/(1000*1000));
			Log.g1("Time to find a path2 : " + time );
			position.setPath(path);
			link.setPath(position);
		}
	}

}
